package com.quanyou.utils;

import java.util.Map;

/**
 * Created by Huangxb on 2016/7/12.
 */
public class BeanUtils {

    /**
     * 如果是null，将返回字符串0
     *
     * @param param
     * @return
     */
    public static String ifNullTo0(String param) {
        if (param == null || param.equals("null")) {
            return "0";
        }
        return param;
    }

    public static void transMap2Bean2(Map<String, Object> map, Object obj) {
        if (map == null || obj == null) {
            return;
        }
        try {
            org.apache.commons.beanutils.BeanUtils.populate(obj, map);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据key数组和value数组拼接json
     *
     * @param keys   key数组
     * @param values value数据
     * @return json
     * @throws Exception
     */
    public static String wrapToJsonByKeyValue(String[] keys, String[] values) throws Exception {
        StringBuilder stringBuilder = new StringBuilder();
        if (keys.length != values.length) {
            throw new Exception("长度不匹配，不能进行JSON格式的转换");
        }
        for (int i = 0; i < keys.length; i++) {
            stringBuilder.append("\"").append(keys[i]).append("\":\"").append(values[i]).append("\",");
        }
        return "{" + stringBuilder.substring(0, stringBuilder.length() - 1) + "}";
    }

}
